<template>
  <common-list>
    <el-row :gutter="10" class="mb8" slot="tools">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['datascan:level:add']"
          >新增
        </el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          @click="handleDelete()"
          v-hasPermi="['datascan:level:remove']"
          :disabled="!showBatch"
          >批量删除
        </el-button>
      </el-col>
    </el-row>

    <common-table
      slot="content"
      v-loading="loading"
      :data="levelList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="级别名称"
        align="left"
        prop="name"
        width="200px"
      />
      <el-table-column
        label="类别"
        align="left"
        prop="boundNames"
        show-overflow-tooltip
      />
      <el-table-column label="级别" align="left" prop="level" width="150px" />
      <el-table-column
        label="备注"
        align="left"
        prop="remark"
        width="240px"
        show-overflow-tooltip
      />
      <el-table-column label="操作" align="left" width="90px">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['datascan:level:edit']"
            >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['datascan:level:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>
    <pagination
      v-show="totalCount > 0"
      :total="totalCount"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <common-edit-dialog
      :title="title"
      :visible.sync="open"
      @cancel="cancel"
      @submit="submitForm"
      :buttonLoading="buttonLoading"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        @submit.native.prevent
      >
        <el-row :gutter="18">
          <el-col :span="24">
            <el-form-item label="级别名称" prop="name">
              <common-input
                v-model="form.name"
                placeholder="请输入"
                :maxlength="16"
                :disabled="this.form.levelId != null"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="级别" prop="level">
              <common-input-number
                :max-length="3"
                class="level"
                v-model="form.level"
                placeholder="敏感级别越高,数值越大,最小值为1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数据类别" prop="typeIds">
              <div class="maxRowsDiv">
                <el-cascader
                  style="width: 100%"
                  :options="treeListArr"
                  v-model="form.typeIds"
                  :show-all-levels="false"
                  :props="{
                    label: 'typeName',
                    value: 'typeId',
                    multiple: true,
                  }"
                  checkStrictly
                  clearable
                >
                  <template slot-scope="{ node, data }">
                    <common-marquee-text
                      :content="data.typeName"
                    ></common-marquee-text>
                  </template>
                </el-cascader>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <common-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </common-edit-dialog>
  </common-list>
</template>

<script>
import CommonList from "@/template/CommonList";
import {
  queryTreeList,
  listLevel,
  getLevel,
  delLevel,
  addLevel,
  updateLevel,
  deleteForCheck,
} from "@/api/datascan/level/level";
import { getParentIdList } from "@/utils/queryParent";
import BaseList from "@/mixins/BaseList";

export default {
  name: "Level",
  mixins: [BaseList],
  components: {
    CommonList,
  },
  data() {
    return {
      totalCount: 0,
      buttonLoading: false,
      treeListArr: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示查询条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据分级表格数据
      levelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 0,
        pageSize: 10,
      },
      // 表单参数
      form: {
        levelId: null,
        name: "",
        level: 1,
        typeIds: [],
        remark: "",
      },
      key: "levelId",
      // 表单校验
      rules: {
        level: [
          {
            required: true,
            message: "请输入级别",
            trigger: "blur",
          },
          {
            type: "number",
            min: 1,
            max: 999,
            message: "级别范围1-999",
            trigger: "blur",
          },
        ],
        name: [{ required: true, message: "请输入级别名称", trigger: "blur" }],
        typeIds: [
          { required: true, message: "请选择数据类别", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.queryTreeList();
    console.log(this.form);
  },
  methods: {
    queryTreeList() {
      queryTreeList(this.queryParams).then((res) => {
        if (res && res.code === 200 && res.data && res.data.length) {
          this.treeListArr = res.data;
        } else {
          this.treeListArr = [];
        }
      });
    },
    /** 查询数据分级列表 */
    getList() {
      this.loading = true;
      listLevel(this.queryParams)
        .then((res) => {
          // console.log(res)
          if (res && res.code === 200) {
            this.levelList = res.data.dataList;
            this.totalCount =
              res && res.data.totalCount ? res.data.totalCount : 0;
          } else {
            this.levelList = [];
            this.totalCount = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        levelId: null,
        name: "",
        level: 1,
        typeIds: [],
        remark: "",
      };
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "新增数据分级";
      this.form.levelId = null;
      this.reset();
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      const levelId = row?.levelId || this.ids;
      getLevel({ levelId }).then((res) => {
        if (res && res.code === 200) {
          // this.form = res.data;
          this.open = true;
          this.title = "编辑数据分级";
          const boundIdsString = row.boundIds;
          let boundIds = boundIdsString
            ? boundIdsString.split(",").map(Number)
            : [];
          let typeIds = [];
          if (boundIds && boundIds.length) {
            boundIds.map((v) => {
              typeIds.push(getParentIdList(this.treeListArr, v));
            });
          }
          let dataObj = Object.assign({}, res.data, { typeIds });
          // row = Object.assign({}, res.data, { typeIds })
          this.$nextTick(() => {
            Reflect.ownKeys(this.form).forEach(
              (k) => (this.form[k] = dataObj[k])
            );
          });
        } else {
          this.$GlobalErrorConfirm("数据加载失败", res.msg);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        let typeIds = [];
        this.form && this.form.typeIds && this.form.typeIds.length
          ? this.form.typeIds.map((v) => {
              // console.log(v);
              typeIds.push(v[v.length - 1]);
            })
          : null;
        if (valid) {
          this.buttonLoading = true;

          // this.form.createTime = undefined
          // this.form.typeIds = typeIds.join(",")
          // this.form.delFlag = undefined
          // this.form.updateTime = undefined
          if (this.form.levelId != null) {
            updateLevel(
              Object.assign({}, this.form, {
                typeIds: typeIds.join(","),
                createTime: undefined,
                delFlag: undefined,
                updateTime: undefined,
              })
            )
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("编辑成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addLevel(
              Object.assign({}, this.form, {
                typeIds: typeIds.join(","),
                updateTime: undefined,
              })
            )
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    deleteData(row) {
      const levelIds = row?.levelId || this.ids.join(",");
      // console.log(levelIds)
      this.$GlobalDeleteConfirm()
        .then(() => {
          delLevel({ levelIds }).then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("删除成功");
              if (
                this.queryParams.pageNum > 1 &&
                levelIds.split(",").length === this.levelList.length
              ) {
                this.queryParams.pageNum -= 1;
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        deleteForCheck({ levelIds: ids })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
};
</script>

<style lang="scss">
.addOrEditClass {
  color: red;
  max-height: 66%;
  overflow-y: auto;

  .maxRowsDiv {
    max-height: 64px;
    overflow-y: auto;
  }
}

.level {
  width: 100% !important;
}
</style>
